//
//  TodoRow.swift
//  memo
//
//  Created by DaleGuo on 2023/10/4.
//

import SwiftUI
import WidgetKit

struct TodoRow: View {
    @EnvironmentObject var homeVM: HomeViewModel
    @ObservedObject var todo: TodoEntity
    @State var offset_todo: CGSize = .zero

    var body: some View {

        HStack {
            TextField("Tick to finish", text: $todo.content, onCommit: {
                homeVM.applyChange()
            })
            .textInputAutocapitalization(.never)
            .textFieldStyle(.plain)
            .submitLabel(.done)
            Spacer()
            Text(todo.updated_date.formatted(date: .omitted, time: .shortened))
                .font(.system(size: 10))
                .foregroundStyle(Color("SecondaryText"))
                .offset(y: 3)

            Button(intent: ToggleStateIntent(id: todo.id)) {
                Image(systemName: todo.is_completed ? "checkmark.circle" : "circle")
            }
            .buttonStyle(.plain)
        }
        .offset(offset_todo)
        .gesture(
            DragGesture()
                .onChanged { value in
                    withAnimation {
                        if abs(value.translation.width) < 50 {
                            offset_todo.width = value.translation.width
                        }
                    }
                }
                .onEnded { value in

                    if value.translation.width > 30 {
                        homeVM.update_todo(todo: todo)
                    }

                    if value.translation.width < -30 {
                        homeVM.delete_todo(todo: todo)
                    }

                    withAnimation {
                        offset_todo = .zero
                    }
                }
        )
        .padding(.leading, todo.level ? 0 : 30)
    }
}

#Preview {
    TodoRow(todo: MemoEntity.example.todos.first!)
}
